package com.bxshey.happyTown.service.impl;

import com.alibaba.fastjson.JSON;
import com.bxshey.happyTown.dto.login.InsertDTO;
import com.bxshey.happyTown.dto.login.LoginDTO;
import com.bxshey.happyTown.entity.User;
import com.bxshey.happyTown.entity.WxChat;
import com.bxshey.happyTown.exception.BusinessException;
import com.bxshey.happyTown.mapper.UserMapper;
import com.bxshey.happyTown.result.ResultEnum;
import com.bxshey.happyTown.service.LoginService;
import com.bxshey.happyTown.utils.JwtUtils;
import com.bxshey.happyTown.vo.login.LoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @作者：不想说话而已
 * @Date：2024/1/4 0:20
 */

@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Resource
    UserMapper userMapper;

    @Value("${wechat.appid}")
    private String APP_ID;

    @Value("${wechat.secret}")
    private String SECRET;

    private final String WX = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 登录
     *
     * @param login 登录用的信息
     * @return 用户信息、令牌
     */
    @Override
    public LoginVO login(LoginDTO login) {
        String openid = getOpenid(login.getCode());
        if(Objects.isNull(openid) || openid.equals("")){
            throw new BusinessException(ResultEnum.ERROR_WX_CODE);
        }
        User user = userMapper.queryOpenid(openid);
        if (Objects.isNull(user)) {
            throw new BusinessException(ResultEnum.ERROR_ENROLL);
        }
        Map<String, String> info = new HashMap<>();
        info.put("id", String.valueOf(user.getId()));
        info.put("username", String.valueOf(user.getUsername()));
        JwtUtils.createToken(info);
        LoginVO loginVo = new LoginVO();
        BeanUtils.copyProperties(user, loginVo);
        loginVo.setToken(JwtUtils.createToken(info));
        return loginVo;
    }


    //获取openid
    String getOpenid(String code){
        //请求路径
        String url = WX + "?appid=" + APP_ID
                + "&secret=" + SECRET
                + "&js_code=" + code
                + "&grant_type=authorization_code";

        //远程请求微信 ，请求微信授权
        RestTemplate restTemplate = new RestTemplate();
        String  forObject = restTemplate.getForObject(url, String.class);
        WxChat wxChat = JSON.parseObject(forObject, WxChat.class);
        return Objects.isNull(wxChat) ? null : wxChat.getOpenid();

    }





    /** 新用户注册
     *
     * @param info 用户信息
     * @return 用户id
     */
    @Override
    public Integer enroll(InsertDTO info) {
        String openid = getOpenid(info.getCode());
        if(Objects.isNull(openid) || openid.equals("")){
            throw new BusinessException(ResultEnum.ERROR_WX_CODE);
        }
        User user = new User();
        user.setOpenid(openid);
        user.setAvatar(info.getAvatar());
        user.setUsername(info.getUsername());
        userMapper.insertOne(user);
        return user.getId();
    }
}
